package recipese.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import recipese.bean.Recipe;

public class RecipeDao extends JpaDao<Recipe> {

	@Override
	public Class<Recipe> getEntityClass() {
		return Recipe.class;
	}

	@SuppressWarnings("unchecked")
	@Transactional(propagation = Propagation.REQUIRES_NEW)
	public List<Recipe> getAll(String userId) {
		final EntityManager entityManager = getEntityManager();
		final StringBuilder builder = new StringBuilder("SELECT o FROM ").append(getEntityClass().getName()).append(" o");
		builder.append(" WHERE o.userId = :userId");
		
		final Query query = entityManager.createQuery(builder.toString());
		query.setParameter("userId", userId);
		
	    return new ArrayList<Recipe>(query.getResultList());
	}
	
	@SuppressWarnings("unchecked")
	@Transactional(propagation = Propagation.REQUIRES_NEW)
	public List<Recipe> getAll(Map<String, Boolean> sortProperties, String userId) {
		final EntityManager entityManager = getEntityManager();
		final StringBuilder builder = new StringBuilder("SELECT o FROM ").append(getEntityClass().getName()).append(" o");
		builder.append(" WHERE o.userId = :userId");
		
		if (sortProperties != null && !sortProperties.isEmpty()) {
			builder.append(" ORDER BY ");

			for (String property : sortProperties.keySet()) {
				
				builder.append(property);
			
				if (sortProperties.get(property)) {
					builder.append(" ASC,");
				} else {
					builder.append(" DESC,");
				}
			}
			
			builder.setLength(builder.length() - 1);
		}
		
		final Query query = entityManager.createQuery(builder.toString());
		query.setParameter("userId", userId);
		
	    return new ArrayList<Recipe>(query.getResultList());
	}
	
}
